import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const takeawayStore = createSlice({
	name: 'takeaway',

	// state
	initialState: {
		foodsList: [], // 商品列表
		cartList: [], // 购物车列表
	},

	// action
	reducers: {
		// 设置商品列表
		setFoodsList(state, action) {
			state.foodsList = action.payload
		},
		// 加入购物车
		addCart(state, action) {
			const item = state.cartList.find((item) => item.id === action.payload.id)
			if (item) {
				item.count++
			} else {
				state.cartList.push(action.payload)
			}
		},
		// 购物车 count +1
		incrementCart(state, action) {
			const item = state.cartList.find((item) => item.id === action.payload.id)
			if (item) {
				item.count++
			}
		},
		// 购物车 count -1
		decrementCart(state, action) {
			const item = state.cartList.find((item) => item.id === action.payload.id)
			if (item && item.count > 1) {
				item.count--
			} else {
				state.cartList = state.cartList.filter((item) => item.id !== action.payload.id)
			}
		},
		// 清空购物车
		clearCart(state) {
			state.cartList = []
		},
	},
})

// 解构 action
const { setFoodsList, addCart, incrementCart, decrementCart, clearCart } = takeawayStore.actions

// 异步 action 获取数据
const fetchFoodsList = () => {
	return async (dispatch) => {
		const res = await axios.get('http://geek.itheima.net/v1_0/channels')
		const foodsList = res.data.data.channels.map((item) => ({
			...item,
			price: Math.floor(Math.random() * 100) + 10,
			count: 1,
		}))

		dispatch(setFoodsList(foodsList))
	}
}

// 导出 action
export { fetchFoodsList, addCart, incrementCart, decrementCart, clearCart }
// 导出 reducer
export default takeawayStore.reducer
